package com.qiji.auth.config;

import com.qiji.auth.component.JwtTokenEnhancer;
import com.qiji.auth.service.impl.UserServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.ArrayList;
import java.util.List;

/**
 * 认证服务器配置
 * Created by macro on 2020/6/19.
 *
 */

/**
 * ClientDetailsServiceConfigurer 能够使用内存或者JDBC来实现客户端详情服务（ClientDetailsService），
 * ClientDetailsService负责查找ClientDetails，而ClientDetails有几个重要的属性如下列表：
 * clientId：（必须的）用来标识客户的Id。
 * secret：（需要值得信任的客户端）客户端安全码，如果有的话。
 * @Configuration
 * @EnableAuthorizationServer
 * public class AuthorizationServer extends
 * AuthorizationServerConfigurerAdapter {
 * //略...
 * }
 * public class AuthorizationServerConfigurerAdapter implements AuthorizationServerConfigurer {
 * public AuthorizationServerConfigurerAdapter() {}
 * public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {}
 * public void configure(ClientDetailsServiceConfigurer clients) throws Exception {}
 * public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {}
 * }
 * 北京市昌平区建材城西路金燕龙办公楼一层 电话：400-618-9090
 * scope：用来限制客户端的访问范围，如果为空（默认）的话，那么客户端拥有全部的访问范围。
 * authorizedGrantTypes：此客户端可以使用的授权类型，默认为空。
 * authorities：此客户端可以使用的权限（基于Spring Security authorities）。
 * 客户端详情（Client Details）能够在应用程序运行的时候进行更新，可以通过访问底层的存储服务（例如将客户
 * 端详情存储在一个关系数据库的表中，就可以使用 JdbcClientDetailsService）或者通过自己实现
 * ClientRegistrationService接口（同时你也可以实现 ClientDetailsService 接口）来进行管理。
 */
@AllArgsConstructor
@Configuration
@EnableAuthorizationServer
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    private final PasswordEncoder passwordEncoder;
    private final UserServiceImpl userDetailsService;
    private final AuthenticationManager authenticationManager;
    private final JwtTokenEnhancer jwtTokenEnhancer;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        /**
         * 暂时使用内存方式存储客户端详细信息
         * 可以配置多个客户端，以认证各个客户端方式
         */
        clients.inMemory()
                // client_id
                .withClient("client-app")
                .secret(passwordEncoder.encode("123456"))
                //允许授权范围
                .scopes("all")
                //该client允许的授权类型 authorization_code权限码
                .authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(86400);
//              回调地址
//                .redirectUris("http://www.baidu.com");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(accessTokenConverter());
        enhancerChain.setTokenEnhancers(delegates); //配置JWT的内容增强器
        endpoints.authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService) //配置加载用户信息的服务
                .accessTokenConverter(accessTokenConverter())
                .tokenEnhancer(enhancerChain);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients();
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        jwtAccessTokenConverter.setKeyPair(keyPair());
        return jwtAccessTokenConverter;
    }

    @Bean
    public KeyPair keyPair() {
        //从classpath下的证书中获取秘钥对
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "123456".toCharArray());
        return keyStoreKeyFactory.getKeyPair("jwt", "123456".toCharArray());
    }

}
